package com.situ.springboot.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//拦截器的作用：浏览器访问服务器的请求，都要首先经过拦截器
public class LoginInterceptor implements HandlerInterceptor {

    //previous
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断用户有没有登录
        //2.如果登录了，就放行，可以正常访问后台资源
        //3.如果没有登录，跳转到登录界面
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user != null) {
            //已经登录，放行
            return true;
        } else {
            //没有登录，跳转到登录界面
            response.sendRedirect("/user/toLogin");
            return false;
        }
    }
}
